import { defineStore } from 'pinia'
import request from '../utils/request'

export const useExamStore = defineStore('exam', {
  state: () => ({
    examList: [], // 试卷列表数据
    currentExam: null, // 当前选中的试卷
    examQuestions: [], // 试卷题目列表
    loading: false // 加载状态标识
  }),
  
  actions: {
    // 获取试卷列表
    async fetchExamList() {
      this.loading = true
      try {
        console.log('发送请求：获取试卷列表')
        const res = await request.post('/bitable/v1/apps/DkMWbAVOeazy5bsjwQbctbd7nqb/tables/tblXvoDOVJQyOL4z/records/search', {
          automatic_fields: false,
          field_names: [
            "未完成考试人员",
            "试卷名称",
            "题库分类",
            "单选数量",
            "多选数量",
            "判断数量",
            "填空数量",
            "简答数量",
            "单选分值",
            "多选分值",
            "判断分值",
            "填空分值",
            "简答分值"
          ],
          view_id: "vewVMF57r9"
        })
        console.log('试卷列表获取成功')
        this.examList = res.data.items
      } catch (error) {
        console.error('获取试卷列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 获取试卷详情
    async fetchExamDetail(examId, category) {
      try {
        console.log('发送请求：获取试卷题目')
        const res = await request.post('/bitable/v1/apps/DkMWbAVOeazy5bsjwQbctbd7nqb/tables/tblk1ggEDhnG603k/records/search', {
          automatic_fields: false,
          field_names: [
            "题型",
            "题目"
          ],
          filter: {
            conditions: [
              {
                field_name: "题库分类",
                operator: "is",
                value: [category]
              }
            ],
            conjunction: "and"
          },
          view_id: "vewMknPnES"
        }, {
          timeout: 30000  // 单独设置这个请求的超时时间
        })
        
        console.log('试卷题目获取成功')
        this.examQuestions = res.data.items
        return res.data
      } catch (error) {
        console.error('获取试卷详情失败:', error)
        // 如果是超时错误，给出更明确的提示
        if (error.code === 'ECONNABORTED') {
          throw new Error('获取题目超时，请检查网络连接后重试')
        }
        return null
      }
    },

    // 提交考试答案
    async submitExamAnswers(answers) {
      try {
        console.log('发送请求：提交考试答案')
        const records = answers.map((item, index) => ({
          fields: {
            "题目ID(工作流)": item.questionId,
            "考试人作答": item.answer,
            "考试人员": [{ "id": item.userId }],
            "考卷已提交标记": "已提交",
            "试卷ID": item.examId,
            "提交考卷(最后填)": index === 0 ? "提交" : ""
          }
        }))
        const res = await request.post('/bitable/v1/apps/DkMWbAVOeazy5bsjwQbctbd7nqb/tables/tblohIphoUumSUU6/records/batch_create', {
          records
        })
        console.log('考试答案提交成功')
        return res.data
      } catch (error) {
        console.error('提交考试答案失败:', error)
        return null
      }
    },

    // 提交考试结果
    async submitExamResult(resultData) {
      try {
        console.log('发送请求：提交考试结果')
        const res = await request.post('/bitable/v1/apps/DkMWbAVOeazy5bsjwQbctbd7nqb/tables/tblaDnKyieW8XJmr/records', {
          fields: {
            "考试人员": [{ "id": resultData.userId }],
            "试卷ID": resultData.examId,
            "开始答题时间": resultData.startTime,
            "花费时长": resultData.duration
          }
        })
        console.log('考试结果提交成功')
        return res.data
      } catch (error) {
        console.error('提交考试结果失败:', error)
        return null
      }
    }
  }
}) 